package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户端拦截器
 *
 * @author makangkang
 * @date 2025/10/22 20:41
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截mvc的方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取Token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        // 如果token为空，返回401
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        // 解析token
        try {
            Claims claims = tokenService.parseToken(token);
            String userId = claims.get("userId").toString();
            // 把userId放在线程局部变量
            UserThreadLocal.set(Long.parseLong(userId));
            // 放行
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 及时销毁线程局部变量
        UserThreadLocal.remove();
    }
}
